package com.yh.workbill.ui.companyInfo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import okhttp3.internal.Util;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.yh.workbill.App;
import com.yh.workbill.R;
import com.yh.workbill.base.BaseActivity;
import com.yh.workbill.databinding.ActivityAddCompanyInfoBinding;
import com.yh.workbill.databinding.LayoutHeadBinding;
import com.yh.workbill.db.Company;
import com.yh.workbill.db.CompanyDao;
import com.yh.workbill.model.JsonBean;
import com.yh.workbill.ui.companyInfo.mvp.AddCompanyInfo_Presenter;
import com.yh.workbill.ui.companyInfo.mvp.AddCompanyInfo_View;
import com.yh.workbill.utils.GetJsonDataUtil;
import com.yh.workbill.utils.Utils;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class AddCompanyInfoActivity extends BaseActivity implements AddCompanyInfo_View {

    private ActivityAddCompanyInfoBinding binding;
    private LayoutHeadBinding layoutHead;
    private AddCompanyInfoViewModel viewModel;
    private AddCompanyInfo_Presenter presenter;
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_company_info);
        layoutHead = binding.layoutHead;

    }

    @Override
    public void initJetPack(@Nullable Bundle savedInstanceState) {
        presenter = new AddCompanyInfo_Presenter(this);
        viewModel = ViewModelProviders.of(this).get(AddCompanyInfoViewModel.class);
        this.getLifecycle().addObserver(presenter);
        binding.setLifecycleOwner(this);

        viewModel.getCity().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!s.equals("请选择")) {
                    binding.clAddress.setVisibility(View.VISIBLE);
                } else {
                    binding.clAddress.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void initObserve(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void initBaseSetting(@Nullable Bundle savedInstanceState) {
        layoutHead.setTitle("添加公司");
    }

    @Override
    public void initClick(@Nullable Bundle savedInstanceState) {
        layoutHead.llBlack.setOnClickListener(v -> finish());
        binding.btnAdd.setOnClickListener(v -> {
            String companyName = binding.etCompanyName.getText().toString().trim();
            String companyPhone = binding.etCompanyPhone.getText().toString().trim();
            String city = binding.tvCompanyCity.getText().toString().trim();
            String address = binding.etCompanyAddress.getText().toString().trim();

            if (TextUtils.isEmpty(companyName)) {
                Utils.ShowToas(AddCompanyInfoActivity.this, "请填写公司名");
                return;
            }
            String subAddress = "";
            if (!TextUtils.isEmpty(address)) {
                subAddress = city + "-" + address;
            } else if (!city.equals("请选择")) {
                subAddress = city;
            }
            presenter.addCompany(companyName, subAddress, companyPhone);
        });
    }

    @Override
    public void initDefaultMethod(@Nullable Bundle savedInstanceState) {
        initJsonData();
        binding.clCity.setOnClickListener(v -> {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(binding.getRoot().getWindowToken(), 0);
            showPickerView();
        });
    }


    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + "-" + opt2tx + "-" + opt3tx;
                binding.tvCompanyCity.setText(tx);
                viewModel.setCity(tx);
            }
        })

                .setTitleText("所在地区")
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setDividerColor(Color.BLACK)
                .setSubmitColor(getResources().getColor(R.color.colorAccent))//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .isAlphaGradient(true)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
            /**
             * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
             * 关键逻辑在于循环体
             *
             * */
            String JsonData = new GetJsonDataUtil().getJson(AddCompanyInfoActivity.this, "province.json");//获取assets目录下的json文件数据

            ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

            /**
             * 添加省份数据
             *
             * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
             * PickerView会通过getPickerViewText方法获取字符串显示出来。
             */
            options1Items = jsonBean;

            for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
                ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

                for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                    String cityName = jsonBean.get(i).getCityList().get(c).getName();
                    cityList.add(cityName);//添加城市
                    ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
            /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                    || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                city_AreaList.add("");
            } else {
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
            }*/
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                    province_AreaList.add(city_AreaList);//添加该省所有地区数据
                }

                ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                    /**
                     * 添加城市数据
                     */
                    options2Items.add(cityList);

                    /**
                     * 添加地区数据
                     */
                    options3Items.add(province_AreaList);
                });
            }


        });
    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    @Override
    public void getData(List<com.yh.workbill.model.Company> data) {

    }

    @Override
    public void addSuccess(String company, String company_address, String company_phone) {
        Utils.ShowToas(this, "添加成功");
        ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
            CompanyDao companyDao = App.appDataBase.getCompanyDao();
            companyDao.add(new Company(company, company_address, company_phone));
        });
        binding.etCompanyName.setText("");
        binding.etCompanyName.setHint("请输入公司名");

        binding.etCompanyPhone.setText("");
        binding.etCompanyPhone.setHint("请输入公司电话");

        binding.tvCompanyCity.setHint("请选择");

        binding.etCompanyAddress.setText("");
        binding.etCompanyAddress.setHint("请输入详细地址");
    }

    @Override
    public void addFail(String msg) {
        Utils.ShowToas(this, msg);
    }

    @Override
    public void queryFail(String msg) {

    }

    @Override
    public void delSuccess(String company_name) {

    }

    @Override
    public void refresh() {

    }

    @Override
    public void loadMore() {

    }

    @Override
    public void getDataFail() {

    }

    @Override
    public void showTasot(String message) {
        Utils.ShowToas(this, message);
    }

    @Override
    public void showDialog(String content, boolean isCancelable) {
        showLoaddingDialog(content, isCancelable);
    }

    @Override
    public void hideDialog() {
        hideLoaddingDialog();
    }
}
